<template>
    <div>
        <el-card>
            <el-form :model="formData" ref="formRef">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="上传附件">
                            <el-upload ref="uploadRef" action="" :file-list="fileList" :limit="1" 
                                :http-request="submitUpload"  :before-upload="beforeUpload">
                                <template #trigger>
                                    <el-button type="primary">选择文件</el-button>
                                </template>
                                <el-button plain :icon="Files" @click="uploadFile"
                                    style="margin-left: 10px;">下载导入模板</el-button>
                                <text>（注：）</text>
                                <el-button type="primary" @click="detailExcel">预览excel</el-button>
                                <el-button type="primary" @click="refExcel">验证excel</el-button>
                                <el-button type="primary" @click="importExcel">导入</el-button>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :xs="8" :sm="12" :md="12" :lg="6" :xl="6">
                        <el-form-item label="数据开始行">
                            <el-input-number v-model="formData.startLineNumber" controls-position="right" />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="8" :sm="12" :md="12" :lg="6" :xl="6">
                        <el-form-item label="工作薄">
                            <el-select v-model="formData.sheetIndex">
                                <el-option v-for="item in options" :key="item.value" :label="item.text" :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="8" :sm="12" :md="12" :lg="6" :xl="6">
                        <el-form-item label="最大列">
                            <el-input-number v-model="formData.maxColNumber" controls-position="right" />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="8" :sm="12" :md="12" :lg="6" :xl="6">
                        <el-form-item label="导入行数">
                            <el-input-number v-model="formData.maxRows" controls-position="right" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :xs="8" :sm="12" :md="12" :lg="6" :xl="6">
                        <el-form-item label="标题所在行">
                            <el-input-number v-model="formData.headRowIndex" controls-position="right" />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="8" :sm="12" :md="12" :lg="6" :xl="6">
                        <el-form-item label="是否导入重复记录">
                            <el-switch v-model="formData.importRepeatRecord	"/>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="8" :sm="12" :md="12" :lg="6" :xl="6">
                        <el-form-item label="忽略重复记录">
                            <el-switch v-model="formData.ignoreRepeatRecord	"/>
                        </el-form-item>
                    </el-col>
                </el-row>
                <sc-title title="设置导入规则"></sc-title>
                <el-table :data="tableData" ref="tableRef">
                    <el-table-column type="index" width="50" />
                    <el-table-column prop="label" label="标题" />
                    <el-table-column prop="fieldName" label="字段名" />
                    <el-table-column prop="column" label="列名">
                        <template #default="scope">
                            <el-select v-model="scope.row.column" size="small">
                                <el-option v-for="node in columnMapList" :key="node.text" :label="node.value"
                                    :value="node.text"></el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form>
        </el-card>
        <el-dialog v-model="visible" fullscreen title="预览" width="80%">
            <!-- <el-table :data="excelData">
                <template v-for="(item, index) in excelConfig" :key="index">
                    <el-table-column :prop="item.prop" :label="item.label" />
                </template>
            </el-table> -->
            <previewExcel v-if="visible == true" :file="file"></previewExcel>
            <!-- <el-pagination background layout="->, prev, pager, next, jumper ,total, " :total="excelRows" :page-size="20"
                @current-change="excelPageChange" /> -->
        </el-dialog>
        <el-dialog v-model="errorVisible" title="错误描述"  width="80%">
            <el-table :data="errorData">
                <el-table-column prop="recordIndex" label="错误行号"></el-table-column>
                <el-table-column prop="msg" label="错误描述"></el-table-column>
            </el-table>
            
            <el-pagination background layout="->, prev, pager, next, jumper ,total, " :total="errorRows" :page-size="20"
                @current-change="errorPageChange" />
        </el-dialog>
    </div>
</template>
<script setup>
import { ref,  onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Files } from '@element-plus/icons-vue'
import { ElNotification, genFileId } from 'element-plus'
import Api from '@/api/model/system.js'
import previewExcel from '@/components/previewExcel/index.vue'
const formData = ref({
    startLineNumber: '',
    sheetIndex: '',
    maxColNumber: '',
    maxRows: '',
    saveAsFileName: '',
    templateFile: '',
    headRowIndex: '',
})
const route = useRoute();
const fileName = ref()
const file = ref()
const fileList = ref()
const tableData = ref()
const uploadRef = ref()
const options = ref({})
const columnMapList = ref({})
const visible = ref(false)
const excelData = ref()
const excelRows = ref(0)
const excelConfig = ref()
const pageNo = ref(1)
const errorVisible = ref(false)
const errorData = ref()
const errorRows = ref(0)
const errorPageNo = ref(1)

onMounted(() => {
    fileName.value = route.query.fileName
    getInit()
})


// const handleExceed = (files) => {
//     console.log(files)
//     uploadRef.value.clearFiles()
//     let file = files[0]
//     file.uid = genFileId()
//     uploadRef.value.handleStart(file)
//     let data = {
//         file: file
//     }
//     file.value = file
//     submitUpload(data)
// }
const beforeUpload = (file) =>{
    return new Promise((resolve, reject) => {
        let suffixArr = file.name.split('.'),
        suffix = suffixArr[suffixArr.length - 1]
		// 判断上传格式*****************
		const isXlsx = suffix === 'xlsx'
		// const isLt10M = file.size / 1024 / 1024 < 10;
		if (!isXlsx ) {
			ElNotification.warning({title:'请上传excel文件'})
			 reject()
		}
        else{
            resolve()
        }
		// if (!isLt10M) {
		// 	alert('上传图片大小不能超过 10MB!');
		// 	 reject()
		// }
    })
}
const getInit = async () => {
    let params = {
        fileName: fileName.value
    }
    let res = await Api.excel.create.post(params)
    formData.value = res.data.importRule
    tableData.value = res.data.columnRuleList
    columnMapList.value = res.data.columnMapList
}

const submitUpload = async (data) => {
    console.log(data)
    file.value = data.file
    let params = {
        file: file.value
    }
    let res = await Api.excel.readSheetList.post(params)
    if (res.code == 200) {
        options.value = res.dataList
    }
    else {
        ElNotification.error({ message: res.msg });
    }
}


const uploadFile = async () => {
    let params = {
        saveAsFileName: formData.value.saveAsFileName,
        downloadFileName: formData.value.templateFile
    }
    let res = await Api.uploadfile.post(params)
}

const detailExcel = async () => {
    visible.value = true
    // let params = {
    //     fileName: fileName.value,
    //     file: file.value,
    //     pageNo: pageNo.value,
    //     pageSize: 20,
    //     beanRule: formData.value
    // }
    // let res = await Api.excel.readSheetData.post(params)
    // if (res.code == 200) {
    //     excelData.value = res.dataList
    //     excelConfig.value = res.headList
    //     visible.value = true
    // }
    // else {
    //     ElNotification.error({ message: res.msg });
    // }
}

const refExcel = async () => {
    let params = {
        file: file.value,
        fileName: fileName.value,
        pageNo: errorPageNo.value,
        pageSize: 20,
        beanRule: formData.value,
        data: {
            columnMapList: tableData.value
        }
    }
    let res = await Api.excel.validate.post(params)
    if(res.code == 10){
        errorData.value = res.reportData
        errorVisible.value = true
    }
    else if(res.code == 200){
        ElNotification.success({ message: res.msg })
    }
    else{
        ElNotification.error({ message: res.msg })
    }
}

const importExcel = async () => {
    let params = {
        file: file.value,
        fileName: fileName.value,
        beanRule: formData.value,
        data: {
            columnMapList: tableData.value
        }
    }
    let res = await Api.excel.import.post(params)
    if(res.code === '200'){
        ElNotification.success({ message: res.msg })
    }
    else if(res.code == 10){
        errorData.value = res.reportData
        errorVisible.value = true
    }
    
}

const excelPageChange = (val) => {
    pageNo.value = val
    detailExcel()
}
const errorPageChange = (val) => {
    errorPageNo.value = val
    refExcel()
}

</script>
<style  scoped>
.link {
    margin-left: 20px;
    margin-bottom: 3px;
}
</style>

